// pages/home/home.js

let template = require('./../../template/tabbar.js');

import moment from "./../../tools/moment"
import debounce from './../../tools/debounce'
import { loginWxAction, globalSetting, userUpdateShareRequest, queryBannersByType, queryCheckIsOpen } from "../../service/config"




import {
  XRLB_IMG,
  SLOGAN_IMG,
  HOMETOPBG_IMG,
  HOMEWODEDIAN_IMG
} from "../../service/image_service"
import {
  FIRST_LOGIN_HOME,
  BIND_USER_ID
} from "../../service/base_service"
//新接口：
import {
  queryHomeFrontConfig,
  queryCategoryProducts,//查询底部商品分类
} from "../../service/jb_home_service"
import {
  queryUserInfo,
} from "../../service/jb_mine_service"
import {
  queryCartCount,

} from "../../service/jb_shopcar_service.js"
import {
  queryAllCoupons,
  receiveCoupon,
  queryNewPersonCoupons,
} from "../../service/jb_coupon_service"
import {
  homeSeckill
} from "../../service/jb_seckill_service.js"
import {
  getFrontUploadSign
} from "../../service/config"

import { queryArticleTags } from "../../service/article_service"
import { queryUserPayInfo } from "../../service/user_service"
import { querySystemNotRead } from "../../service/msg_service"
import {
  bindSpread,
  notReadMsgNumber
} from "../../service/jb_common_service"
import { MAP_KEY } from "../../service/base_service"

import { newHomeMenu, queryRoleConfig } from "../../service/onetoone_service"
const JB_BANNER = 'jb_banner'
const JB_DISPLAY = 'jb_display'
const app = getApp()


Page({

  /**
   * 页面的初始数据
   */
  data: {
    xrlb_img: XRLB_IMG,
    ylBanner: "https://images.jiabao19.com/home/ylbanner.png",
    slogan_img: SLOGAN_IMG,
    homeTopBg_img: HOMETOPBG_IMG,
    homewodedian_img: HOMEWODEDIAN_IMG,
    themeStyle: "",
    scrollTop: 0,
    showNewModule: true,//显示新房模块
    showNewPersonPop: false,
    navBarTopBgImg: "https://saas.img.ylyc.top/bg/newhometopbg_icon.png",//顶部导航栏背景图
    noRecevieCouponbg: 'https://images.jiabao19.com/home/xinryhquan.png',//优惠券未选择的情况
    receviedCouponbg: '',
    scrollTopValue: 0,//scroll到顶部的绝对定位距离
    menuTop: app.globalData.menuButton.top,
    menuHeight: app.globalData.menuButton.height,
    navBarHeight: app.globalData.menuButton.top + app.globalData.menuButton.height,
    mapKey: MAP_KEY,
    isAdView: false,//是否展示开屏广告
    bottomTabs: [

    ],
    notReadNum: 0,
    currentBottomTab: { type: 1 },//当前选中的tabs
    bottomTabPage: 1,//底部商品列表分页
    bottomProductList: [],
    //底部请求所有新房房源
    requestData: {
      cityName: "",
      houseStyle: "",
      maxArea: null,
      maxTotalPrice: null,
      maxUnitPrice: null,
      minArea: null,
      minTotalPrice: null,
      minUnitPrice: null,
      page: 0,
      pageSize: 10,
      saleStatus: "",
      subway: "",
      tags: [],
      words: "",
      zone: ""
    },


    adData: {},//开屏广告data
    countDownNum: 5,

    // 顶部swiper
    indicatorDots: true,
    indicatorActiveColor: '#0071FF',
    autoplay: true,
    interval: 5000,
    duration: 1000,
    circular: true,
    bannerUrls: [
      // {
      //   "name": "春节快乐",
      //   "pic": "https://jyhky.ylyc.top/expert/1681108441993-banner.jpg",
      //   "id": 1528,
      //   "url": "/pages/news_details/index?id=17"
      // },
      // {
      //   "name": "开心",
      //   "pic": "https://jyhky.ylyc.top/expert/1681109206403-banner.jpg",
      //   "id": 1529,
      //   "url": "/pages/goods_list/index?cid=245&title=热门推荐"
      // },
      // {
      //   "name": "快乐",
      //   "pic": "https://jyhky.ylyc.top/expert/1683619519760-BANNER.jpg",
      //   "id": 1530,
      //   "url": "/pages/goods_details/index?id=8"
      // }
    ],

    // 顶部swiper


    roleType: 1,//用户等级类型
    newDynPage: 0,
    newsDynList: [],//房友圈数据
    scrollRefreshStatus: true,
    //新房的顶部显示模块
    newTopModules: [

    ],
    plaNewTopModules: [
      { type: 1 }, { type: 1 }, { type: 1 }, { type: 1 }, { type: 1 },
    ],
    //滑块模块
    slideModules: [

    ],
    slideModulesPlas: [
      "1", "1", "1", "1", "1"
    ],
    //滑块指示器
    sildeIndicatorList: [

    ],
    bottomDynList: [],//房友圈数据
    totalNotReadNumber: 0,
    scrollLeft: 0,//左右滑动scoll距离




    displayArr: [
      // {
      //   icon: "/img/common/home/bsbs_icon.png",
      //   title: "补水保湿",
      // },
      // {
      //   icon: "/img/common/home/shxf_icon.png",
      //   title: "术后修复",
      // },
      // {
      //   icon: "/img/common/home/kyqd_icon.png",
      //   title: "控油祛痘",
      // },
      // {
      //   icon: "/img/common/home/dlks_icon.png",
      //   title: "冻龄抗衰",
      // },
      // {
      //   icon: "/img/common/home/smxf_icon.png",
      //   title: "舒敏修护",
      // },
      // {
      //   icon: "/img/common/home/mbdb_icon.png",
      //   title: "美白淡斑",
      // }
    ],
    horizontalArr: [
      // [
      //   {
      //     icon: "/img/common/home/srns_icon.png",
      //     title: "水乳面霜",
      //   },
      //   {
      //     icon: "/img/common/home/mbxl_icon.png",
      //     title: "面膜系列",
      //   },
      //   {
      //     icon: "/img/common/home/yyjh_icon.png",
      //     title: "原液精华",
      //   },
      //   {
      //     icon: "/img/common/home/fsgl_icon.png",
      //     title: "防晒隔离",
      //   },
      //   {
      //     icon: "/img/common/home/ybhl_icon.png",
      //     title: "眼部护理",
      //   }
      // ],
      // [
      //   {
      //     icon: "/img/common/home/yyjh_icon.png",
      //     title: "原液精华",
      //   },
      //   {
      //     icon: "/img/common/home/fsgl_icon.png",
      //     title: "防晒隔离",
      //   },
      //   {
      //     icon: "/img/common/home/ybhl_icon.png",
      //     title: "眼部护理",
      //   },
      //   {},
      //   {},
      // ]
    ],


    isShowLoading: false,//加载状态出现
    isBottomShow: false,//是否没有更多数据了
    bottomSwitchIndex: 0,//底部默认是底部的新房

    bindUserId: "",//绑定关系的userId,
    isScanEnter: false,//是否是扫码进来的
    isShare: false,//是否分享进来的


    // 悬浮相关
    newScrollTop: 0,
    newOffsetTop: 0,
    toView: "",
    isFriend: 0,//是否是朋友圈分享进来的
    lanuchObj: {},//小程序启动参数



    bigSwiperTitles: [

    ],
    countTimestamp: 0, //倒计时时间戳

    bigSwiperIndex: 0,//大轮播图位置
    bigSwiperIntoViewStr: 'bigSwiper-0',
    //首页秒杀配置
    homeSeckillConfig: null,
    homeSeckillList: [],
    couponList: [],//优惠券列表
    isLogin: true,//是否登录，登录了就不是新人，未登录，就是未绑定手机号就是新人
    newPersonCoupons: [],
    newPersonMoney: 0,//新人券总和
    isCanTop: false,//是否显示滚动到顶部
    scrollTopNum: 0,
    refreshFlag: false,
    showRegisterPop: false,
    isFirstOnShow: true,
    isShowRegister: false,//注册邀请弹窗只有刷新整个首页才出现一次哈，未登录的
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log("JJLog:首页参数:" + JSON.stringify(options));
    wx.JJLog("首页参数:" + JSON.stringify(options))


    this.setData({
      bannerUrls: wx.getStorageSync(JB_BANNER) || [],
      displayArr: wx.getStorageSync(JB_DISPLAY) || []
    })

    let lanuchObj = wx.getLaunchOptionsSync();









    this.setData({
      lanuchObj: lanuchObj,
    })
    if (options.isFriend == 1) {
      this.setData({
        isFriend: 1,
        bindUserId: options.userId,
      })
      wx.setStorageSync(BIND_USER_ID, options.userId)
      wx.setNavigationBarTitle({
        title: '佳宝19',
      })

    }
    //点击朋友圈分享里面的前往小程序按钮
    if (lanuchObj.scene == 1155) {
      this.setData({
        isFriend: 0,
      })
    }
    template.tabbar("tabBar", 0, this, 0)//0表示第一个tabbar
    // 监听主题配置改变:
    // getApp().watchThemeStyle(this.watchThemeStyleBack)
    //scrollTop顶部计算:
    this.scrollTopCalculate();

    //开屏广告
    if (this.data.isFriend == 0) {
      //this.queryOpenBannersByType();
    }

    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    wx.hideTabBar();

    if (options.scene) {
      let scene = decodeURIComponent(options.scene)
      console.log("JJLog:9999999==========:" + scene);
      let sceneArray = scene.split("&");
      // let secondArr = sceneArray[1].split("=");
      // let threeArr = sceneArray[2].split("=");
      // let b = secondArr[1];
      // if (b == 1) {
      //   this.setData({
      //     isScanEnter: true
      //   })
      // }
      let userId = sceneArray[1];
      wx.setStorageSync(BIND_USER_ID, userId)
      console.log("JJog:进入首页绑定的userId:" + userId);
      this.setData({
        bindUserId: userId,
        isShare: true
      })
    }
    if (options.isShare && options.userId) {
      this.setData({
        isScanEnter: false,
        isShare: true,
        bindUserId: options.userId
      })
      wx.setStorageSync(BIND_USER_ID, options.userId)
      console.log("JJog:进入首页绑定的userId======:" + options.userId);
    }

    // 绑定分享参数
    wx.onCopyUrl(() => {
      console.log("JJLog:绑定分享参数了============")
      return { query: `userId=${app.globalData.userId}&isShare=1` }
    })


  },
  //跳转视力养护
  pushToYL() {
    wx.navigateTo({
      url: '/featurePackage/pages/eyeLove/eyeLove',
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    // this.otherUserWxLogin()
    //wx-openId登录
    this.userWxLogin();




  },
  onHide() {
    wx.offCopyUrl()
  },
  watchThemeStyleBack: function (themeStyle) {
    // console.log('监听到的主题配置是:' + themeStyle);
    this.setData({
      themeStyle: themeStyle
    })
  },

  // onPageScroll(e) {
  //   this.setData({ scrollTop: e.scrollTop });
  // },



  //登录获取唯一openId:
  //用户登陆授权等:
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data;
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh()
      if (res.code == 200) {
        // this.userLocationAuthJudge();
        app.globalData.nickName = data.nickName;
        app.globalData.avatar = data.avatar || [];
        // app.globalData.name = data.name || "";
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.userId = data.uid
        app.globalData.isBind = data.isBind || null
        this.setData({
          scrollRefreshStatus: false,
          isLogin: data.isLogin
        })

        // if (app.globalData.isFirstEnter) {
        //   //是第一次进来:
        //   this.userUpdateShareRequest();
        // }
        // this.queryCheckIsOpen();
        if (data.isLogin) {
          // this.getFrontUploadSign();
          this.notReadMsgNumber();
          this.queryCartCount();
        }
        if (!data.isLogin && !this.data.isShowRegister) {
          this.setData({
            showRegisterPop: true,
            isShowRegister: true,
          })
        }


        // 判断是否需要绑定关系:
        // let firstLoginHome = wx.getStorageSync(FIRST_LOGIN_HOME);
        //未绑定的才调用接口
        if (data.isLogin) {
          if (!data.isBind) {
            let bindUserId = wx.getStorageSync(BIND_USER_ID);
            if (bindUserId && bindUserId != '') {
              // this.bindUserRelation(bindUserId);
            }
          }
          this.queryUserInfo();
          //确实从登录过后切换到首页来的

        }



        //临时调用一下，要放在login之后调用
        this.queryHomeConfig();
        this.getHomeSeckill();
        //获取所有的优惠券：
        this.queryAllCoupons();
        if (!data.isLogin) {
          this.queryNewPersonCoupons();
        }
        //获取全局配置:

        // this.queryRoleConfig();
        //存储openId到global
        app.globalData.openId = wx.getStorageSync('openId');





      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh()
      this.setData({
        scrollRefreshStatus: false
      })
    })
  },
  //获取个人信息api
  queryUserInfo() {
    queryUserInfo().then(res => {
      if (res.code == 200) {
        app.globalData.userInfo = res.data
      }
    }).catch(err => {
      console.error("JJLog:queryUserInfo", err);
    })
  },
  //倒计时完成
  countTimeFinish() {
    this.getHomeSeckill();
  },
  getFrontUploadSign() {
    getFrontUploadSign().then(res => {
      console.log("JJLog:获取到的图片签名是:" + JSON.stringify(res));
      if (res.code == 200) {
        wx.setStorageSync('ossHost', res.data.host);
        wx.setStorageSync('ossSignature', res.data.signature);
        wx.setStorageSync('ossPolicy', res.data.policy);
        wx.setStorageSync('ossAccessId', res.data.accessId);
        wx.setStorageSync('ossCallBack', res.data.callback);
        wx.setStorageSync('ossDir', res.data.dir);
      }
    }).catch(err => {
      console.error("JJLog:getFrontUploadSign", err);
    })
  },
  queryAllCoupons() {
    queryAllCoupons().then(res => {
      // console.log("JJLog:获取到的优惠券是:" + JSON.stringify(res));
      if (res.code == 200) {
        //过滤一下，只有用户未领取的才显示：
        if (res.data && res.data.list && res.data.list.length > 0) {
          let arr = [];
          res.data.list.forEach(i => {
            if (!i.isUse) {
              arr.push(i)
            }
          })
          this.setData({
            couponList: arr
          })
        } else {
          this.setData({
            couponList: []
          })
        }

      }
    }).catch(err => {
      console.error("JJLog:queryAllCoupons", err);
    })
  },
  pushToMoreActivity() {
    wx.switchTab({
      url: '/pages/activity/activityList',
    })
  },
  notReadMsgNumber() {
    notReadMsgNumber().then(res => {
      if (res.code == 200) {
        this.setData({
          notReadNum: res.data.notRead || 0
        })
      }
    }).catch(err => {

    })
  },
  queryNewPersonCoupons() {
    queryNewPersonCoupons().then(res => {
      console.log("JJLog:新人券:" + JSON.stringify(res));
      this.setData({
        newPersonCoupons: res.data.list || []
      })
      if (res.data && res.data.list && res.data.list.length > 0) {
        let arr = res.data.list;
        let newPersonMoney = 0;
        arr.forEach(i => {
          newPersonMoney = newPersonMoney + parseInt(i.money)
        })
        this.setData({
          newPersonMoney: newPersonMoney
        })
      }
    }).catch(err => {
      console.error("JJLog:queryNewPersonCoupons:", err);
    })
  },
  //绑定挂级关系:
  bindUserRelation(id) {
    console.warn("JJLog:传入绑定关系参数:" + JSON.stringify(id));
    wx.setStorageSync(FIRST_LOGIN_HOME, false);
    bindSpread(id).then(res => {
      console.log("JJLog:绑定挂级关系成功:" + JSON.stringify(res));
      wx.setStorageSync(BIND_USER_ID, '');
    }).catch(err => {
      console.error("JJLog:bindSpread===============:", err);
    })
  },
  //回到顶部方法
  scrollToTopAction() {
    this.setData({
      scrollTopNum: 0
    })
  },
  otherUserWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data.data;
      if (res.code == 200) {
        app.globalData.nickName = data.nickName;
        app.globalData.avatar = data.avatar;
        app.globalData.name = data.name || "";
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.userId = data.id;
        app.globalData.isAuthUserInfo = data.isAuthUserInfo;
        app.globalData.weChat = data.weChat || "";
        app.globalData.roleName = data.roleName || "";
        app.globalData.qrCode = data.qrCode || "";
        app.globalData.companyName = data.companyName || "";
        app.globalData.companyNumber = data.companyNumber || "";
        app.globalData.isBindMp = data.isBindMp;
        app.globalData.roleType = data.roleType || 0
        this.setData({
          scrollRefreshStatus: false,
          roleType: app.globalData.roleType
        })
        // template.tabbar("tabBar", 0, this, app.globalData.unreadCount, this.data.roleType)//0表示第一个tabbar

      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);
      this.setData({
        scrollRefreshStatus: false
      })
    })
  },
  userUpdateShareRequest() {
    userUpdateShareRequest().then(res => {
      wx.setStorageSync('firstEnter', true);
    }).catch(err => {
      console.error("JJLog:userUpdateShareRequest", err);
    })
  },

  //查询是否:
  queryCheckIsOpen() {
    queryCheckIsOpen().then(res => {
      if (res.code == 200) {
        console.log("JJLog:check状态:" + JSON.stringify(res));
        app.globalData.isCheckOpen = res.data;
      }
    }).catch(err => {
      console.error("JJLog:check:err:" + JSON.stringify(err));
    })
  },


  // 大轮播图切换了
  bigSwiperChange(e) {
    // console.log("JJLog:切换内容是:" + JSON.stringify(e));
    if (e.detail.source == 'autoplay' || e.detail.source == 'touch') {
      // console.log("JJLog:来没有啊======");
      this.setData({
        bigSwiperIndex: e.detail.current,
        bigSwiperIntoViewStr: 'bigSwiper-' + e.detail.current,
      })
    }

  },
  bigSwiperClick(e) {
    // let index = e.currentTarget.dataset.index;
    // this.setData({
    //   bigSwiperIndex: index,
    //   bigSwiperIntoViewStr: 'bigSwiper-' + index,
    // })
  },
  queryRoleConfig() {
    queryRoleConfig().then(res => {
      console.log("JJLog:角色配置是==:" + JSON.stringify(res));
      if (res.code == 200) {
        app.globalData.roleConfig = res.data.role;
      }
    }).catch(err => {
      console.log("JJLog:角色配置失败====:" + JSON.stringify(err));
    })
  },

  pushToOfficalPage() {
    //跳转webView
    // app.globalData.webUrl = app.globalData.wxMpLink;
    // wx.navigateTo({
    //   url: '/pages/webViewPage/webViewPage',
    // })
    wx.navigateTo({
      url: '/firstPackage/pages/officialAccounts/officialAccounts',
    })
  },

  pushToRichContent(e) {
    let item = e.currentTarget.dataset.item;
    if (item.type == 1) {
      app.globalData.webUrl = item.url
      wx.navigateTo({
        url: '/pages/webViewPage/webViewPage',
      })
    } else {
      wx.navigateTo({
        url: '/shopMallPackage/pages/richDetailPage/richDetailPage?id=' + item.id + "&title=" + item.title + '&isBottom=' + 0,
      })
    }

  },
  pushToBottomRichDetail(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/shopMallPackage/pages/richDetailPage/richDetailPage?id=' + id + "&title=" + '详情' + '&isBottom=' + 1,
    })
  },


  //新闻列表头部tags:
  queryArticleTags() {
    queryArticleTags().then(res => {
      console.log("JJLog:新闻tags:" + JSON.stringify(res));
      if (res.code == 200) {
        app.globalData.articleTags = res.data || []
      }
    }).catch(err => {
      console.error("JJLog:queryArticleTags:", err);
    })
  },
  queryOfficalQrCode() {
    queryOfficalQrCode().then(res => {
      console.log("JJLog:公众号:" + JSON.stringify(res));
      if (res.code == 200) {
        app.globalData.officalQrCode = res.data || "";
      }
    }).catch(err => {
      console.error("JJLog:queryOfficalQrCode", err);
    })
  },
  //获取这个支付结算信息
  queryUserPayInfo() {
    queryUserPayInfo().then(res => {
      console.log("JJLog:支付信息==:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data) {
          let obj = {
            openName: res.data.openName || "",
            bankName: res.data.bankName || "",
            openBank: res.data.openBank || "",
            bankAccount: res.data.bankAccount || "",
            businessLicenseImg: res.data.businessLicenseImg || "",
            cardFront: res.data.cardFront || "",
            cardBack: res.data.cardBack || "",
            isEdit: res.data.isEdit,
            id: res.data.id || "",
            wxUserId: res.data.wxUserId || ""
          }
          app.globalData.userPayInfo = obj;
        } else {
          let obj = {
            openName: "",
            bankName: "",
            openBank: "",
            bankAccount: "",
            businessLicenseImg: "",
            cardFront: "",
            cardBack: "",
            isEdit: true,
            id: "",
            wxUserId: ""
          }
          app.globalData.userPayInfo = obj;
        }

      }
    }).catch(err => {
      console.error("JJLog:queryUserPayInfo", err);
    })
  },



  /** 请求相关方法 */

  /** 响应相关方法 */
















  /** 配置相关方法 */

  //配置 scrollView 到顶部距离
  scrollTopCalculate() {
    let top = 0;
    if (this.data.showNewModule) {
      //新房模块作为首页
      top = app.globalData.menuButton.top + app.globalData.menuButton.height + 40 + 13 + 10;
    } else {
      top = 200;
    }
    // console.log("JJLog:去赋值的height:" + top);
    this.setData({
      scrollTopValue: top
    })

  },




  //点击跳转页面:
  pushToPage(e) {
    let type = e.currentTarget.dataset.type;
    if (type == "youhui") {
      wx.navigateTo({
        url: '/firstPackage/pages/flashSale/flashSale',
      })
    }
  },








































  //scroll滚动到底了:
  scrolltolower() {
    console.log("JJLog:到底了==========");
    if (this.data.isBottomShow) {
      //已经到底了就不加载了
      return;
    }
    this.setData({
      bottomTabPage: this.data.bottomTabPage + 1,
      isShowLoading: true,
    })
    this.queryBottomProducts('false', true)
  },
  //scroll下拉刷新:
  refreshDownData() {
    // console.log("JJLog:下拉来了==========");

    this.userWxLogin();
  },









  //系统消息未读数量
  querySystemNotRead() {
    querySystemNotRead().then(res => {
      // console.log("JJLog:系统消息未读数量:" + JSON.stringify(res));
      if (res.code == 200) {
        let num = res.data || 0;
        let totalNum = this.data.totalNotReadNumber;
        if (num > 0) {
          totalNum = totalNum + num;
          this.setData({
            totalNotReadNumber: totalNum,
          })
          app.globalData.unreadCount = this.data.totalNotReadNumber;
          // template.tabbar("tabBar", 0, this, app.globalData.unreadCount, this.data.roleType)//0表示第一个tabbar
        }


      }
    }).catch(err => { })
  },



  onScroll(event) {
    wx.createSelectorQuery()
      .select('#scroller')
      .boundingClientRect((res) => {
        this.setData({
          newScrollTop: event.detail.scrollTop,
          newOffsetTop: res.top,
        });
      })
      .exec();

    // 判断是否显示回到顶部按钮
    if (event.detail.scrollTop > 300) {
      this.setData({
        isCanTop: true
      });
    } else {
      this.setData({
        isCanTop: false
      });
    }
  },
  onPullDownRefresh: function () {
    //展示加载动画
    wx.showNavigationBarLoading()
    // console.log("JJLog:下拉来了==========");
    this.setData({
      'requestData.page': 0,
      newsPage: 0,
      isBottomShow: false,
      scrollRefreshStatus: true,
    })
    this.userWxLogin();

  },
  // 位置授权相关=========;
  //用户位置授权判断:
  userLocationAuthJudge() {
    return;
    // 位置获取授权判断
    let that = this;
    wx.getSetting({
      success: res => {
        // 已授权
        if (res.authSetting['scope.userLocation']) {
          console.log('已授权定位')
          // that.getUserPosition()
        } else if (res.authSetting['scope.userLocation'] === undefined) {
          console.log('初次授权定位')
          // 尚未授权
          // that.getUserPosition()
        } else if (res.authSetting['scope.userLocation'] === false) {
          console.log('拒绝授权定位')
          wx.showModal({
            title: '提示',
            content: '平台部分功能需要您的位置授权',
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting['scope.userLocation']) {
                      console.log('打开设置授权定位')
                      // that.getUserPosition()
                    }
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
                wx.showToast({
                  title: '取消位置授权，会影响部分功能使用哦!',
                  icon: "none"
                })
              }
            }
          })
        }
      }
    })

  },

  //JJ-TODO 查询首页配置
  queryHomeConfig() {
    queryHomeFrontConfig().then(res => {
      // console.log("JJLog:首页配置是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data.banner && res.data.banner.length > 0) {
          this.setData({
            bannerUrls: res.data.banner
          })
          wx.setStorageSync(JB_BANNER, res.data.banner);
        }
        //金刚区赋值
        if (res.data.menus && res.data.menus.length > 0) {
          this.setData({
            displayArr: res.data.menus
          })
          wx.setStorageSync(JB_DISPLAY, res.data.menus);
          app.globalData.displayArr = res.data.menus
        }
        //横向滚动标签页赋值:
        if (res.data.productTags && res.data.productTags.length > 0) {
          this.dealProductTags(res.data.productTags)
        }

        if (res.data.explosiveMoney && res.data.explosiveMoney.length > 0) {
          let arr = [{ name: '全部', type: 0 }, ...res.data.explosiveMoney]
          this.setData({
            currentBottomTab: res.data.explosiveMoney[0]
          })
          // let arr = res.data.explosiveMoney;
          arr.forEach(i => {
            i.title = i.name
          })
          this.setData({
            bottomTabs: arr,//底部切换
          })
          // if (this.data.isFirstOnShow) {
          //   this.setData({
          //     isFirstOnShow: false,
          //   })
          //   return;
          // }
          if (this.data.bottomProductList.length > 0) {
            return;
          }
          this.queryBottomProducts('refresh', false);
        }
      }
    }).catch(err => {
      console.error("JJLog:queryHomeFrontConfig", err);
    })
  },
  //处理横向滚动赋值：
  dealProductTags(arr) {
    let result = [];
    for (let i = 0; i < arr.length; i += 5) {
      // slice方法不会改变原数组，而是返回一个新的数组片段
      const chunk = arr.slice(i, i + 5);
      result.push(chunk);
    }
    result.forEach(i => {
      if (i.length < 5) {
        for (let j = i.length; j < 5; j++) {
          i.push({})
        }
      }
    })
    this.setData({
      horizontalArr: result
    })
  },

  //查询底部类型列表
  queryBottomProducts(refresh, isLoading) {
    if (!this.data.currentBottomTab) {
      return;
    }
    if (isLoading) {
      wx.showLoading()
    }
    queryCategoryProducts(this.data.currentBottomTab.type, this.data.bottomTabPage).then(res => {
      wx.hideLoading()
      // console.log("JJLog:底部类型列表是:" + JSON.stringify(res));

      if (res.code == 200 && res.data) {
        let arr = (refresh == 'refresh' ? [] : this.data.bottomProductList || []);
        arr = arr.concat(res.data.list || [])
        this.setData({
          bottomProductList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.bottomTabPage ? true : false,
        })
      }
    }).catch(err => {
      wx.hideLoading()
      if (this.data.bottomTabPage != 1) {
        this.setData({
          bottomTabPage: this.data.bottomTabPage - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
      console.error("JJLog:queryCategoryProducts", err);
    })
  },
  handleTabClick(e) {
    //console.log("JJLog:点击tab切换来了：" + JSON.stringify(e))
    let index = e.detail.index;
    if (this.data.bottomTabs.length > 0) {
      this.setData({
        currentBottomTab: this.data.bottomTabs[index],
        bottomTabPage: 1,
      })
      //还要重置这个loding这些，然后重新请求数据
      this.queryBottomProducts('refresh', true);
    }

  },
  //获取首页秒杀数据
  getHomeSeckill() {
    homeSeckill().then(res => {
      //console.log("JJLog:秒杀数据是：" + JSON.stringify(res))
      if (res.code == 200 && res.data) {
        this.setData({
          homeSeckillConfig: res.data.secKillResponse,
          homeSeckillList: res.data.productList || []
        })
        if (res.data.secKillResponse.timeSwap) {
          this.setData({
            countTimestamp: this.data.homeSeckillConfig.timeSwap
          })
        }
      } else {
        this.setData({
          homeSeckillConfig: null,
          homeSeckillList: []
        })
      }
    }).catch(err => {
      console.error("JJLog:homeSeckill", err)
    })
  },

  //跳转至我的小店
  pushToSmallShop() {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    wx.navigateTo({
      url: '/featurePackage/pages/mySmallShop/mySmallShop',
    })
  },
  //获取开屏广告
  queryOpenBannersByType() {
    queryBannersByType(7).then(res => {
      //console.log("JJLog:开屏广告是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data && res.data.length > 0) {
          this.setData({
            adData: res.data[0],
            isAdView: true
          })
          let number = 6;
          let inter = setInterval(() => {
            number = number - 1;
            this.setData({
              countDownNum: number,
            })
            if (number == 0) {
              this.setData({
                isAdView: false,
              })
              clearInterval(inter)
            }
          }, 1000);
        }
      }
    }).catch(err => {
      console.error("JJLog:queryBannersByType", err);
    })
  },



  //广告跳转:
  adPushToDetail(e) {
    let path = e.currentTarget.dataset.path;
    if (path) {
      wx.navigateTo({
        url: path
      })
    }

  },
  //关闭广告:
  closeAdAction() {
    this.setData({
      isAdView: false,
    })
    app.globalData.isAdView = false;
  },



  // 位置授权相关==========



  pushToFriendPage() {
    wx.navigateTo({
      url: '/firstPackage/pages/friendSharePage/friendSharePage',
    })
  },



  pushToPage(e) {
    let type = e.currentTarget.dataset.type;
    let urlPath = "";
    if (type == 'seckill') {
      urlPath = "/featurePackage/pages/seckillList/seckillList"
    }
    wx.navigateTo({
      url: urlPath,
    })
  },




  newPersonPopChange(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      showNewPersonPop: index == 1 ? true : false,
    })
  },
  closeRegisterPop() {
    this.setData({
      showRegisterPop: false
    })
  },
  pushToLogin() {
    this.setData({
      showNewPersonPop: false,
    })
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  //跳转到领券中心
  pushToCouponCenter() {
    wx.navigateTo({
      url: "/featurePackage/pages/getCouponList/getCouponList"
    })
  },
  //领取优惠券：
  getCouponAction(e) {
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    wx.showLoading();
    receiveCoupon({ couponId: id }).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        let arr = this.data.couponList;
        wx.showToast({
          title: "领取成功",
          icon: "success"
        })
        arr.splice(index, 1)
        this.setData({
          couponList: arr
        })
      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:receiveCoupon", err)
      wx.showToast({
        title: err || '领取失败',
        icon: "none"
      })
    })
  },

  //查询购物车数量
  queryCartCount() {
    queryCartCount().then(res => {
      console.log("JJLog:查询购物车数量" + JSON.stringify(res));
      if (res.code == 200) {
        // this.setData({
        //   cartTotalNum: res.data.count
        // })
        app.globalData.cartNum = res.data.count || 0
        template.tabbar("tabBar", 0, this, app.globalData.cartNum)//0表示第一个tabbar
      }
    }).catch(err => {
      console.log("JJLog:queryCartCount", err);
    })
  },
  pushToInvite() {
    this.setData({
      showRegisterPop: false,
    })
    wx.navigateTo({
      url: '/featurePackage/pages/inviteWxService/inviteWxService',
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let path = "/pages/home/home?isShare=1" + "&userId=" + app.globalData.userId
    return {
      title: app.globalData.commonShareTitle,
      path: path
    }
  },
  onShareTimeline: function () {
    return {
      title: app.globalData.commonShareTitle,
      query: "isFriend=1" + "&userId=" + app.globalData.userId,

    }
  },
})